package com.example.park;

import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;


/*
public class TcpClient {
    private static TcpClient instance;
    private Socket socket;
    private OutputStream outputStream;
    private final String serverIp = "47.98.42.43";
            //"47.98.42.43";
    private final int serverPort = 8889;
    private InputStream inputStream;

    private TcpClient() {}

    public static synchronized TcpClient getInstance() {
        if (instance == null) {
            instance = new TcpClient();
        }
        return instance;
    }

    public void connect() {
        new Thread(() -> {
            try {
                if (socket == null || socket.isClosed()) {
                    socket = new Socket();
                    socket.connect(new InetSocketAddress(serverIp, serverPort), 5000);
                    outputStream = socket.getOutputStream();
                    Log.d("TcpClient", "TCP 连接成功");
                    //sendMessage("Hello Server from Android App");
                } else {
                    Log.d("TcpClient", "已连接，不重复连接");
                }
            } catch (IOException e) {
                Log.e("TcpClient", "连接服务器失败: " + e.getMessage());
                e.printStackTrace();
            }
        }).start();
    }

    public void sendMessage(String message) {
        new Thread(() -> {
            try {
                if (outputStream != null) {
                    outputStream.write(message.getBytes());
                    outputStream.flush();
                    Log.d("TcpClient", "消息已发送：" + message);
                }
            } catch (IOException e) {
                Log.e("TcpClient", "发送消息失败: " + e.getMessage());
            }
        }).start();
    }

    public String receiveMessage() {
/*
        if (socket == null || socket.isClosed() || inputStream == null) {
            Log.e("TcpClient", "接收失败：连接未建立或已关闭");
            return null;
        }

        try {
            socket.setSoTimeout(5000); // 设置读取超时时间为5秒（可调整）
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = reader.readLine(); // 阻塞直到收到一行或超时
            Log.d("TcpClient", "收到服务器消息：" + line);
            return line;
        } catch (IOException e) {
            Log.e("TcpClient", "接收消息失败: " + e.getMessage());
            return null;
        }*//*
        try {
            if (socket != null && socket.isConnected()) {
                InputStream inputStream = socket.getInputStream();
                byte[] buffer = new byte[1024];
                int length = inputStream.read(buffer); // 会阻塞直到有数据
                if (length > 0) {
                    String received = new String(buffer, 0, length, StandardCharsets.UTF_8);
                    Log.d("TcpClient", "接收到原始数据: " + received);
                    return received;
                } else {
                    Log.d("TcpClient", "连接已关闭或无数据");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("TcpClient", "接收消息异常: " + e.getMessage());
        }
        return null;
    }

    public void close() {
        try {
            if (socket != null && !socket.isClosed()) {
                socket.close();
                socket = null;
                Log.d("TcpClient", "TCP 连接已关闭");
            }
        } catch (IOException e) {
            Log.e("TcpClient", "关闭连接失败: " + e.getMessage());
        }
    }
}


 */


public class TcpClient {
    private static TcpClient instance;
    private Socket socket;
    private OutputStream outputStream;
    private InputStream inputStream;
    private final String serverIp = "47.98.42.43";
    private final int serverPort = 8889;

    private boolean isConnecting = false;
    private boolean keepTrying = true;

    private TcpClient() {
        startReconnectThread();  // 启动重连线程
    }

    public static synchronized TcpClient getInstance() {
        if (instance == null) {
            instance = new TcpClient();
        }
        return instance;
    }

    public void connect() {
        new Thread(() -> {
            try {
                if ((socket == null || socket.isClosed() || !socket.isConnected()) && !isConnecting) {
                    isConnecting = true;
                    socket = new Socket();
                    socket.connect(new InetSocketAddress(serverIp, serverPort), 5000);
                    outputStream = socket.getOutputStream();
                    inputStream = socket.getInputStream();
                    Log.d("TcpClient", "TCP 连接成功");
                }
            } catch (IOException e) {
                Log.e("TcpClient", "连接服务器失败: " + e.getMessage());
            } finally {
                isConnecting = false;
            }
        }).start();
    }

    public void sendMessage(String message) {
        new Thread(() -> {
            try {
                if (socket != null && socket.isConnected() && outputStream != null) {
                    outputStream.write(message.getBytes());
                    outputStream.flush();
                    Log.d("TcpClient", "消息已发送：" + message);
                } else {
                    Log.e("TcpClient", "发送失败：未连接");
                    connect();  // 尝试重连
                }
            } catch (IOException e) {
                Log.e("TcpClient", "发送消息失败: " + e.getMessage());
                connect();  // 出错时尝试重连
            }
        }).start();
    }

    public String receiveMessage() {
        try {
            if (socket != null && socket.isConnected() && inputStream != null) {
                byte[] buffer = new byte[1024];
                int length = inputStream.read(buffer); // 阻塞直到有数据或断开
                if (length > 0) {
                    String received = new String(buffer, 0, length, StandardCharsets.UTF_8);
                    Log.d("TcpClient", "接收到原始数据: " + received);
                    return received;
                } else {
                    Log.d("TcpClient", "连接已关闭或无数据");
                    connect();  // 无数据，可能断开，尝试重连
                }
            } else {
                connect();  // 没连接，尝试重连
            }
        } catch (IOException e) {
            Log.e("TcpClient", "接收消息异常: " + e.getMessage());
            connect();  // 异常时尝试重连
        }
        return null;
    }

    public void close() {
        try {
            keepTrying = false;  // 停止重连
            if (socket != null && !socket.isClosed()) {
                socket.close();
                socket = null;
                Log.d("TcpClient", "TCP 连接已关闭");
            }
        } catch (IOException e) {
            Log.e("TcpClient", "关闭连接失败: " + e.getMessage());
        }
    }

    private void startReconnectThread() {
        new Thread(() -> {
            while (keepTrying) {
                try {
                    if (socket == null || socket.isClosed() || !socket.isConnected()) {
                        Log.d("TcpClient", "检测到断开，尝试重连...");
                        connect();
                    }
                    Thread.sleep(5000);  // 每5秒检查一次
                } catch (InterruptedException e) {
                    Log.e("TcpClient", "重连线程中断: " + e.getMessage());
                }
            }
        }).start();
    }



    private boolean isSocketAlive() {
        try {
            if (socket == null || socket.isClosed() || !socket.isConnected()) {
                return false;
            }

            // 主动发送一个心跳测试包（可以用 \0 或 PING）
            socket.getOutputStream().write(0);  // 写一个字节，不影响服务端处理
            socket.getOutputStream().flush();
            return true;
        } catch (IOException e) {
            return false;  // 出错就说明连接已断
        }
    }
}




